package cn.accjiyun.controller.admin;

import cn.accjiyun.core.cache.EHCacheUtil;
import cn.accjiyun.core.constants.CommonConstants;
import cn.accjiyun.core.controller.BaseController;
import cn.accjiyun.core.utils.CacheConstans;
import cn.accjiyun.core.utils.MD5;
import cn.accjiyun.core.utils.SingletonLoginUtils;
import cn.accjiyun.core.utils.WebUtils;
import cn.accjiyun.model.system.LoginLog;
import cn.accjiyun.model.system.SysUser;
import cn.accjiyun.service.LoginLogService;
import cn.accjiyun.service.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;

/**
 * Created by jiyun on 2017/2/3.
 */
@Controller
@RequestMapping("/admin")
public class LoginController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    private static String loginPage = getViewPath("/admin/main/login");//后台登录页面
    private static String loginSuccess = "redirect:/admin/main/main";//后台管理主界面

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private LoginLogService loginLogService;

    @InitBinder({"sysUser"})
    public void initBinderSysUser(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("sysUser.");
    }

    @RequestMapping
    public ModelAndView login() {
        return new ModelAndView(loginPage);
    }

    /**
     * 执行登录
     *
     * @param request
     * @return ModelAndView
     */
    @RequestMapping("/main/login")
    public ModelAndView login(HttpServletRequest request, HttpServletResponse response, @ModelAttribute("sysUser") SysUser sysUser) {
        ModelAndView model = new ModelAndView();
        model.setViewName(loginPage);
        try {
            model.addObject("sysUser", sysUser);
            if (sysUser.getLoginName() == null || sysUser.getLoginName().trim().equals("")) {
                model.addObject("message", "请输入用户名!");
                return model;
            }
            if (sysUser.getLoginPwd() == null || sysUser.getLoginPwd().trim().equals("")) {
                model.addObject("message", "请输入密码!");
                return model;
            }

            //获取Session中验证码
            String randCode = (String) request.getSession().getAttribute(CommonConstants.RAND_CODE);
            //用户输入的验证码
            String randomCode = request.getParameter("randomCode");
            if (randomCode == null || !randomCode.equals(randCode)) {
                model.addObject("message", "验证码不正确！");
                return model;
            }
            request.getSession().removeAttribute(CommonConstants.RAND_CODE);
            sysUser.setLoginPwd(MD5.getMD5(sysUser.getLoginPwd()));
            SysUser su = sysUserService.queryLoginUser(sysUser);
            if (su == null) {
                model.addObject("message", "用户名或密码错误！");
                return model;
            }
            if (su.getStatus() == 0) {
                model.addObject("message", "该账号已被禁用！");
                return model;
            }
            //缓存用登录信息
            EHCacheUtil.set(CacheConstans.LOGIN_MEMCACHE_PREFIX + su.getUserId(), su);
            WebUtils.setCookie(response, CacheConstans.LOGIN_MEMCACHE_PREFIX, CacheConstans.LOGIN_MEMCACHE_PREFIX + su.getUserId(), 1);

            //修改用户登录记录
            Timestamp nowTime = new Timestamp(System.currentTimeMillis());
            LoginLog loginLog = new LoginLog();
            loginLog.setUserId(su.getUserId());
            loginLog.setLoginTime(nowTime);
            loginLog.setIpAddress(WebUtils.getIpAddr(request));
            loginLogService.createLoginLog(loginLog);
            sysUserService.updateUserLoginLog(su.getUserId(), nowTime, WebUtils.getIpAddr(request));
            model.setViewName(loginSuccess);
        } catch (Exception e) {
            model.addObject("message", "系统繁忙，请稍后再操作！");
            logger.error("login()--error", e);
        }
        return model;
    }

    /**
     * 后台用户退出登录
     *
     * @param request
     * @param response
     */
    @RequestMapping("/outLogin")
    public String outLogin(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.getSession().invalidate();
            int userId = SingletonLoginUtils.getLoginSysUserId(request);
            //删除所有的权限缓存
            EHCacheUtil.remove(CacheConstans.SYS_ALL_USER_FUNCTION_PREFIX + userId);
            //删除登录用户的缓存信息
            EHCacheUtil.remove(CacheConstans.LOGIN_MEMCACHE_PREFIX + userId);
            //删除登录用户权限缓存
            EHCacheUtil.remove(CacheConstans.USER_FUNCTION_PREFIX + userId);
            //删除页面用户Cookie
            WebUtils.deleteCookie(request, response, CacheConstans.LOGIN_MEMCACHE_PREFIX);
            //清空所有的Session
            request.getSession().invalidate();
        } catch (Exception e) {
            logger.error("outLogin()---error", e);
            return this.setExceptionRequest(request, e);
        }
        return "redirect:/admin/";
    }

}
